package com.atguigu.spzx.user.service.impl;

import com.atguigu.spzx.common.interceptor.SpzxUserInfoInterceptor;
import com.atguigu.spzx.model.entity.user.UserAddress;
import com.atguigu.spzx.user.mapper.RegionMapper;
import com.atguigu.spzx.user.mapper.UserAddressMapper;
import com.atguigu.spzx.user.service.UserAddressService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
@Service
public class UserAddressServiceImpl implements UserAddressService {
    @Resource
    UserAddressMapper userAddressMapper;
    @Resource
    RegionMapper regionMapper;
    @Override
    public List<UserAddress> findUserAddressList() {
        //获取用户id
        Long userId = SpzxUserInfoInterceptor.THREAD_LOCAL.get().getId();

        List<UserAddress> userAddressList = userAddressMapper.findUserAddressList(userId);
        return userAddressList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(UserAddress userAddress) {
        //参数校验： 收件人地址、名称 电话 都不能为空
        Long userId = SpzxUserInfoInterceptor.THREAD_LOCAL.get().getId();
        //如果新增的地址为默认的，设置当前用户其他的地址取消默认
        Integer isDefault = userAddress.getIsDefault();
        if(isDefault.intValue()==1){
            userAddressMapper.cancelUserAddressDefaultByUserId(userId);
        }

        userAddress.setUserId(userId);
        String fullRegionName = regionMapper.findFullRegionNameByCode(userAddress.getDistrictCode());
        //查询省市区 名称 和 address拼接
        userAddress.setFullAddress(fullRegionName+userAddress.getAddress());
        userAddress.setCreateTime(new Date());
        userAddress.setUpdateTime(new Date());

        userAddressMapper.save(userAddress);



    }

    @Override
    public UserAddress findUserAddressById(Long id) {

        return userAddressMapper.findUserAddressById(id);
    }
}
